package com.zhaopin.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.apache.pulsar.shade.org.apache.http.HttpEntity;
import org.apache.pulsar.shade.org.apache.http.HttpStatus;
import org.apache.pulsar.shade.org.apache.http.NameValuePair;
import org.apache.pulsar.shade.org.apache.http.client.config.RequestConfig;
import org.apache.pulsar.shade.org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.pulsar.shade.org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.pulsar.shade.org.apache.http.client.methods.HttpGet;
import org.apache.pulsar.shade.org.apache.http.client.methods.HttpPost;
import org.apache.pulsar.shade.org.apache.http.entity.StringEntity;
import org.apache.pulsar.shade.org.apache.http.impl.client.CloseableHttpClient;
import org.apache.pulsar.shade.org.apache.http.impl.client.HttpClients;
import org.apache.pulsar.shade.org.apache.http.message.BasicNameValuePair;
import org.apache.pulsar.shade.org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by lietou1986 on 2017/2/6.
 */
public class HttpUtils {

    private static Logger logger = Logger.getLogger(HttpUtils.class);

    public static boolean post(String url, String data) {
        return post(url, data, 2000);
    }


//    public static JSONObject post3(String url, String data, int time) {
//        boolean flag = false;
//        CloseableHttpClient httpclient = HttpClients.createDefault();
//
//        CloseableHttpResponse response = null;
//        try {
//            HttpPost httpPost = new HttpPost(url);
//            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(time).setConnectTimeout(time).build();
//            httpPost.setConfig(requestConfig);
//            StringEntity myEntity = new StringEntity(data, "UTF-8");
//            httpPost.addHeader("Content-Type", "text/plain");
//            httpPost.setEntity(myEntity);
//            response = httpclient.execute(httpPost);
//            HttpEntity entity = response.getEntity();
//            int scode = response.getStatusLine().getStatusCode();
//            if (scode == HttpStatus.SC_OK) {
////                flag = true;
//            }
//            String responStr = EntityUtils.toString(response.getEntity());
//            EntityUtils.consume(entity);
//            return JSON.parseObject(responStr);
//        } catch (Exception e) {
////            logger.error("http post error ||" + url  + " || "+  data, e);
//            logger.error("http post error ||" + url );
//        } finally {
//            try {
//                if (response != null)
//                    response.close();
//                if (httpclient != null)
//                    httpclient.close();
//            } catch (Exception e) {
//            }
//        }
//
//        return new JSONObject();
//    }

    public static String post3(String url, String data, int time) {
        boolean flag = false;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(time).setConnectTimeout(time).build();
            httpPost.setConfig(requestConfig);
            StringEntity myEntity = new StringEntity(data, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(myEntity);
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            int scode = response.getStatusLine().getStatusCode();
            if (scode == HttpStatus.SC_OK) {
//                flag = true;
            }
            String responStr = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(entity);
            return responStr;
        } catch (Exception e) {
            logger.error("http post error ||" + url);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (Exception e) {
            }
        }

        return "";
    }

    public static JSONObject post2Json(String url, String data, int time) {
        boolean flag = false;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(time).setConnectTimeout(time).build();
            httpPost.setConfig(requestConfig);
            StringEntity myEntity = new StringEntity(data, "UTF-8");
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.setEntity(myEntity);
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            int scode = response.getStatusLine().getStatusCode();
            if (scode == HttpStatus.SC_OK) {
//                flag = true;
            }
            String responStr = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(entity);
            return JSON.parseObject(responStr);
        } catch (Exception e) {
//            logger.error("http post error ||" + url  + " || "+  data, e);
            logger.error("http post error ||" + url);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (null != httpclient) {
                    httpclient.close();
                }
            } catch (Exception e) {
            }
        }

        return new JSONObject();
    }

    public static JSONObject post2(String url, String data, int time) {
        boolean flag = false;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(time).setConnectTimeout(time).build();
            httpPost.setConfig(requestConfig);
            StringEntity myEntity = new StringEntity(data, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(myEntity);
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            int scode = response.getStatusLine().getStatusCode();
            if (scode == HttpStatus.SC_OK) {
//                flag = true;
            }
            String responStr = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(entity);
            return JSON.parseObject(responStr);
        } catch (Exception e) {
//            logger.error("http post error ||" + url  + " || "+  data, e);
            logger.error("http post error ||" + url);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (Exception e) {
            }
        }

        return new JSONObject();
    }


    public static boolean post(String url, String data, int time) {
        boolean flag = false;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(time).setConnectTimeout(time).build();
            httpPost.setConfig(requestConfig);
            StringEntity myEntity = new StringEntity(data, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(myEntity);
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            int scode = response.getStatusLine().getStatusCode();
            if (scode == HttpStatus.SC_OK) {
//                flag = true;
            }
            logger.info("response: " + EntityUtils.toString(response.getEntity()));
            String responStr = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(responStr);
            logger.info("responStr:" + responStr);
            if (jsonObject.getJSONObject("responseHeader").get("status").toString().equals("0")) {
                logger.info("response: " + jsonObject.toJSONString());
                flag = true;
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
//            logger.error("http post error ||" + url  + " || "+  data, e);
            logger.error("http post error ||" + url);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (Exception e) {
                logger.error("http post error ||" + url + " || " + data, e);
            }
        }

        return flag;
    }


    public static String post(String url, Map<String, String> data) {
        return post(url, data, 20000);
    }

    public static String post(String url, Map<String, String> data, int time) {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response = null;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : data.keySet()) {
            nvps.add(new BasicNameValuePair(key, data.get(key)));
        }
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(time).setConnectTimeout(time).build();
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            response = httpclient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(entity.getContent()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                reader.close();
                return sb.toString();
            }
        } catch (Exception e) {
            logger.error("http post error ||" + url + " || " + data, e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (Exception e) {
                logger.error("http post error ||" + url + " || " + data, e);
            }
        }
        return null;
    }

    public static String get(String url) {
        return get(url, 2000);
    }

    public static String get(String url, int time) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(time).setConnectTimeout(time).build();
            httpGet.setConfig(requestConfig);
            response = httpclient.execute(httpGet);
            int scode = response.getStatusLine().getStatusCode();
            if (scode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String returnStr = EntityUtils.toString(entity);
//                logger.info("http get OK" + ":" + returnStr);
                return returnStr;
            }
        } catch (Exception e) {
            logger.error("http get error ||" + url, e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (Exception e) {
                logger.error("http get error ||" + url, e);
            }
        }
        return null;
    }

    public static String postParam(String urlStr, String param) {
        return postParam(urlStr, param, 2000);
    }

    public static String postParam(String urlStr, String param, int time) {

        if (urlStr == null) {
            return null;
        }
        if (urlStr.indexOf("http://") == -1) {
            urlStr = "http://" + urlStr;
        }
        URL url;
        HttpURLConnection con = null;
        StringBuffer result = new StringBuffer();
        try {
            url = new URL(urlStr);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setConnectTimeout(time);

            con.getOutputStream().write(param.getBytes());
            con.getOutputStream().flush();
            con.getOutputStream().close();
            InputStream in = con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line + System.getProperty("line.separator"));
            }

        } catch (Exception e) {
            logger.error("http post param error ||" + urlStr + "||" + param, e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return result.toString();
    }
}
